package com.glorystone.ins.controller;

import com.glorystone.ins.common.JsonResult;
import com.glorystone.ins.common.common.DataTable;
import com.glorystone.ins.common.common.PageVo;
import com.glorystone.ins.domain.Attachment;
import com.glorystone.ins.domain.BusinessLog;
import com.glorystone.ins.domain.Channel;
import com.glorystone.ins.domain.SysUser;
import com.glorystone.ins.enums.FlowBusinessTypeEnum;
import com.glorystone.ins.enums.FlowOperateTypeEnum;
import com.glorystone.ins.enums.WorkFlowEnum;
import com.glorystone.ins.interceptor.PageList;
import com.glorystone.ins.service.*;
import com.glorystone.ins.vo.ChannelCountVo;
import com.glorystone.ins.vo.ChannelHandleVO;
import com.glorystone.ins.vo.ChannelVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by wangwei on 2018/3/6.
 * @author wangwei
 */
@Slf4j
@Controller
@RequestMapping("/channel")
public class ChannelController extends BaseController {

    @Autowired
    private AuditTaskService auditTaskService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private ISysRoleService iSysRoleService;
    @Autowired
    private BusinessLogService businessLogService;
    @Autowired
    private AttachmentService attachmentService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ISysUserService sysUserService;


    /**
     * 渠道首页
     * @return
     */
    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public String toChannelHome(Model model) {
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        Channel channel = channelService.findByUserId(user.getTid());
        log.info("<--info 渠道首页， channel is null?-->{}", channel == null);
        if (channel != null) {
            ChannelCountVo channelCount = orderService.countChannelOrderInfo(channel.getTid());
            log.debug("<--渠道 channel.companyRegisterName-->{}, channel.contact-->{}, channelCount-->{}", channel.getCompanyRegisterName(), channel.getContact(), channelCount);
            model.addAttribute("channelCount", channelCount);
        } else {
            log.warn("<--该用户不存在渠道信息！ 用户-->{}", user);
        }
        SysUser sysUser = sysUserService.getUserById(user.getTid());
    	model.addAttribute("landTime", sysUser.getFirstLand());
    	model.addAttribute("tid", user.getTid());
        return "channel/channel_home";
    }


    @RequiresPermissions("cust:channel:view")
    @RequestMapping(value = "/tolist/{types}", method = RequestMethod.GET)
    public String toChannelView(Model model, Integer nodeId, Long businessId, @PathVariable String types) {
        if(!"P".equals(types)){
            types="C";
        }
        List<SysUser> list = iSysRoleService.getUserListByDepartmentId(RoleTypeIdEnum.BUSSNESSAll.getValue());
        model.addAttribute("list",list);
        model.addAttribute("nodeId",nodeId);
        model.addAttribute("businessId",businessId);
        model.addAttribute("types",types);

        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        Channel channel = channelService.findByUserId(user.getTid());
        if (channel != null) {
            // 渠道用户
            model.addAttribute("channelType", channel.getType());
        }

        return "channel/channel_list";
    }

    @RequiresPermissions(value = "channel:company:edit")
    @RequestMapping(value = "/company/to_edit/{tid}", method = RequestMethod.GET)
    public String toEdit(@PathVariable("tid") Long tid, Model model) {
        //获取所有业务部人员
        List<SysUser> list = iSysRoleService.getUserListByDepartmentId(RoleTypeIdEnum.BUSSNESSAll.getValue());
        List<Attachment> attachmentList = attachmentService.queryAttachList(tid, Attachment.BusinessTypeEnum.CHANNEL.getValue());
        Channel channel = channelService.getById(tid);
        SysUser sysUser=sysUserService.selectById(channel.getUserId().longValue());
        model.addAttribute("list",list);
        model.addAttribute("attachmentList", attachmentList);
        model.addAttribute("channel", channel);
        model.addAttribute("sysUser",sysUser);

        return "channel/channel_edit_company";

    }

    @RequiresPermissions(value = "channel:personal:edit")
    @RequestMapping(value = "/personal/to_edit/{tid}", method = RequestMethod.GET)
    public String toEditPerList(@PathVariable("tid") Long tid, Model model) {
        //获取所有业务部人员
        List<SysUser> list = iSysRoleService.getUserListByDepartmentId(RoleTypeIdEnum.BUSSNESSAll.getValue());
        List<Attachment> attachmentList = attachmentService.queryAttachList(tid, Attachment.BusinessTypeEnum.CHANNEL.getValue());
        Channel channel = channelService.getById(tid);
        SysUser sysUser=sysUserService.selectById(channel.getUserId().longValue());
        model.addAttribute("list",list);
        model.addAttribute("attachmentList", attachmentList);
        model.addAttribute("channel", channel);
        model.addAttribute("sysUser",sysUser);

        return "channel/channel_edit_personal";

    }

    @RequestMapping(value = "/{tid}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<Channel> findById(@PathVariable("tid") Long tid, Model model) {
        Channel channel = channelService.getById(tid);
        return new ResponseEntity<>(channel, HttpStatus.OK);

    }


    @RequiresPermissions(value = {
            "channel:company:create_audit",
            "channel:company:credit_apply",
            "channel:company:credit_first",
            "channel:company:credit_last",
            "channel:company:upload_contract",
            "channel:company:credit_review",
            "channel:company:deposit_ensure",
            "channel:company:deposit_supplement"}, logical = Logical.OR)
    @RequestMapping(value = "/handle", method = RequestMethod.POST)
    public String handelOperate(ChannelHandleVO handleVO,
                                @RequestParam(required = false) MultipartFile businessLicenseFile,
                                @RequestParam(required = false) MultipartFile industryLicenseFile,
                                @RequestParam(required = false) MultipartFile[] legalPersonFile,
                                @RequestParam(required = false) MultipartFile[] seniorManagerFile,
                                @RequestParam(required = false) MultipartFile[] actualControllerFile,
                                @RequestParam(required = false) MultipartFile[] contactsFile) {
        channelService.handle(handleVO, businessLicenseFile, industryLicenseFile, legalPersonFile, seniorManagerFile, actualControllerFile, contactsFile);
        return "redirect:/channel/tolist/C";

    }

    /**
     * 组装公司渠道数据
     * @param request
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value="/queryTableData",method = RequestMethod.GET)
    @ResponseBody
    public DataTable<Channel> queryTableData(HttpServletRequest request){
        PageVo vo =  parametToPageVo(request, Channel.class);
        PageList<Channel> list = channelService.findList(vo);
        DataTable data = resultToDataTable(list);
        return data;
    }

    /**
     * 渠道编辑
     */
    @RequiresPermissions(value = "channel:company:edit")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public String update(ChannelVO channelVO,
                         @RequestParam MultipartFile businessLicenseFile,
                         @RequestParam MultipartFile industryLicenseFile,
                         @RequestParam MultipartFile[] legalPersonFile,
                         @RequestParam MultipartFile[] seniorManagerFile,
                         @RequestParam MultipartFile[] actualControllerFile,
                         @RequestParam MultipartFile[] contactsFile,
                         @RequestParam MultipartFile[] file,
                         String[] alias){


       Channel channel = new ChannelVO().convert(channelVO);
        channelService.update(channel, businessLicenseFile, industryLicenseFile, legalPersonFile, seniorManagerFile, actualControllerFile, contactsFile,file, alias);

        return "redirect:/channel/tolist/C";
    }

    /**
     * 新建渠道
     */
    @RequiresPermissions("channel:create")
    @RequestMapping(value = "/saveChannel",method = RequestMethod.POST)
    @ResponseBody
    public boolean saveChannel(ChannelVO channelVO,
                         @RequestParam(required = false) MultipartFile businessLicenseFile,
                         @RequestParam(required = false) MultipartFile industryLicenseFile,
                         @RequestParam MultipartFile[] legalPersonFile,
                         @RequestParam MultipartFile[] seniorManagerFile,
                         @RequestParam MultipartFile[] actualControllerFile,
                         @RequestParam MultipartFile[] contactsFile,
                         @RequestParam MultipartFile[] file,
                         String[] alias){
        Channel channel = new ChannelVO().convert(channelVO);
        boolean result=false;
        try {
            channelService.saveChannel(channel, businessLicenseFile, industryLicenseFile, legalPersonFile, seniorManagerFile, actualControllerFile, contactsFile,file, alias);
            businessLogService.save(BusinessLog.BusinessTypeEnum.CHANNEL,channel.getTid(),BusinessLog.ContentEnum.CREATE_CHANNEL,null);
            auditTaskService.submit(WorkFlowEnum.CREATE_CHANNEL, FlowBusinessTypeEnum.CHANNEL,channel.getTid(), FlowOperateTypeEnum.START);
            result=true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 渠道编辑
     */
    @RequiresPermissions("channel:personal:edit")
    @RequestMapping(value = "/updatePreChannel",method = RequestMethod.POST)
    public String updatePreChannel(ChannelVO channelVO,
                         @RequestParam MultipartFile businessLicenseFile,
                         @RequestParam MultipartFile industryLicenseFile,
                         @RequestParam MultipartFile[] legalPersonFile,
                         @RequestParam MultipartFile[] seniorManagerFile,
                         @RequestParam MultipartFile[] actualControllerFile,
                         @RequestParam MultipartFile[] contactsFile,
                         @RequestParam MultipartFile[] file,
                         String[] alias){


        Channel channel = new ChannelVO().convert(channelVO);
        channelService.updatePreChannel(channel, businessLicenseFile, industryLicenseFile, legalPersonFile, seniorManagerFile, actualControllerFile, contactsFile,file, alias);
        businessLogService.save(BusinessLog.BusinessTypeEnum.CHANNEL,channel.getTid(),BusinessLog.ContentEnum.EDIT,null);
        auditTaskService.submit(WorkFlowEnum.EDIT_CHANNEL, FlowBusinessTypeEnum.CHANNEL,channel.getTid(), FlowOperateTypeEnum.START);
        return "redirect:/channel/tolist/P";
    }

    /**
     * 工号校验
     */
    @RequestMapping("/onlyJobNumber")
    public @ResponseBody
    JsonResult onlyJobNumber(String jobNumber){
        log.info("-------传入参数jobNumber------"+jobNumber);
        SysUser user = sysUserService.onlyJobNumber(jobNumber);
        if(user==null){
            return returnSuccess("账号还没注册");
        }else{
            return JsonResult.createErrorMsg("账号已经注册");
        }
    }

    /**
     * 查询渠道名称
     */
    @RequestMapping(value = "/findAllChannelName/{name}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult findAllChannelName(@PathVariable("name") String name) {
        log.info("-------传入参数name------"+name);
        List<Channel> channel = channelService.findAllChannelName(name);
        if(channel.size()==0){
            return JsonResult.createErrorMsg("请重新输入渠道名称");
        }else{
            return JsonResult.createSuccess(channel);
        }

    }

    @RequiresPermissions(value = {"channel:personal:delete", "channel:company:delete"}, logical = Logical.OR)
    @RequestMapping(value = "/delete/{tid}", method = RequestMethod.GET)
    public String delete(@PathVariable("tid") Long tid) {
        channelService.deleteById(tid);
        return "redirect:/channel/tolist/C";
    }


}
